package dataClean;

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author Smartloe
 * @create 2021-05-03 18:17
 */
public class ParseXML {
    public static void main(String[] args) {
        /**
         * java以w3c.DOM方式读取xml文件
         */
        String soucePath = "C:\\Users\\25392\\Desktop\\Java基础\\src\\main\\java\\dataClean\\data\\parsexml.xml";
        org.w3c.dom.Document doc = ParseXML.useDomReadXml(soucePath);
        //读取xml内部节点集合
        org.w3c.dom.NodeList nlst = doc.getElementsByTagName("book");
        //遍历集合内容
        for(int i = 0; i < nlst.getLength(); i++)
        {
            String title = doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue();
            String creater = doc.getElementsByTagName("author").item(i).getFirstChild().getNodeValue();
            String year = doc.getElementsByTagName("year").item(i).getFirstChild().getNodeValue();
            String price = doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
            System.err.println("标题:"+ title);
            System.err.println("作者:"+creater);
            System.err.println("年份:"+ year);
            System.err.println("价格:"+ price);
        }
    }


    /**
     * java读取xml文件四中方式之一
     * w3c.DOM方式实现
     */
    public static Document useDomReadXml(String soucePath){
        File file = new File(soucePath);
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            return builder.parse(file);
        } catch (Exception e) {
            System.err.println("读取该xml文件失败");
            e.printStackTrace();
        }
        return null;
    }

}
